#include <iostream>
#include <functional>
#include <string>
#include <unordered_map>
#include "../muduo/include/muduo/net/TcpServer.h"
#include "../muduo/include/muduo/net/EventLoop.h"
using namespace std;

class DictServer
{
public:
    DictServer(int port) : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
                                   "DictServer", muduo::net::TcpServer::kReusePort)
    {
        // 修改回调函数绑定
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _server.start();
        _baseloop.loop();
    }

private:
    // 修改参数类型为 TcpConnectionPtr
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected()) // 使用 -> 操作符访问成员
        {
            cout << "链接已建立" << endl;
        }
        else
        {
            cout << "链接已关闭" << endl;
        }
    }

    string translate(const string &msg)
    {
        static std::unordered_map<std::string, std::string>
            dict_map = {
                {"Hello", "你好"},
                {"你好", "Hello"},
                {"World", "世界"},
                {"世界", "World"},
            };
        auto it = dict_map.find(msg);
        if (it == dict_map.end())
        {
            return "UnKnow";
        }
        return it->second;
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp time)
    {
        string msg = buffer->retrieveAllAsString();
        string ret = translate(msg);
        conn->send(ret);
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main()
{
    DictServer server(8088);
    server.start();
    return 0;
}